package com.yunduo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunduo.common.JwtUtils;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.Address;
import com.yunduo.entity.User;
import com.yunduo.mapper.AddressMapper;
import com.yunduo.service.AddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户地址管理 服务实现类
 * </p>
 *
 * @author ChengXin
 * @since 2023-08-18
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {


    //修改地址
    @Transactional
    @Override
    public boolean updateAddress(Address address) {
        //本地缓存获取用户
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if (address.getPreset()) {
            Address isExist = this.getOne(new LambdaQueryWrapper<Address>().eq(Address::getUserId, user.getId()).eq(Address::getPreset, true));
            if(isExist!=null){
                isExist.setPreset(false);
                this.updateById(isExist);
            }
        }
        this.updateById(address);
        return true;
    }

    //新增地址
    @Override
    public boolean addAddress(Address address) {
        //本地缓存获取用户
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if (address.getPreset()) {
            Address isExist = this.getOne(new LambdaQueryWrapper<Address>().eq(Address::getUserId, user.getId()).eq(Address::getPreset, true));
            if(isExist!=null){
                isExist.setPreset(false);
                this.updateById(isExist);
            }
        }
        this.save(address);
        return true;
    }
}
